package com.clps.rulesregulations.service.impl;

import com.clps.rulesregulations.dao.UserRoleDao;
import com.clps.rulesregulations.domain.Role;
import com.clps.rulesregulations.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户角色逻辑处理实现类
 * @author 张超
 * @date 2017/7/11
 */
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public void updateUserRole(Integer userId,List<Integer> roleIds) {
        userRoleDao.delUserRoleByUserId(userId);
        if(roleIds!=null && !roleIds.isEmpty()){
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId);
            map.put("roleIds",roleIds);
            userRoleDao.addUserRoles(map);
        }
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userRoleDao.findRoleIdsByUserId(userId);
    }

    @Cacheable(cacheNames="roles",key="#userId.toString()")
    @Override
    public List<Role> loadUserRoles(Integer userId) {
        return userRoleDao.loadUserRoles(userId);
    }
}
